package com.smarkparking.controller;

import com.smarkparking.tool.OverDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/redis")
public class RedisController {
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("visit")
    public Integer addUserNumber(HttpSession session) {
        Integer num = (Integer) redisTemplate.opsForValue().get(session.getAttribute("userSession"));
        if (num == null) {
            //设置值到redis
            redisTemplate.opsForValue().set(session.getAttribute("userSession"), 1, OverDate.overTime(), TimeUnit.SECONDS);
        } else {
            //从redis获取值
            Integer number = (Integer) redisTemplate.opsForValue().get(session.getAttribute("userSession"));
            //设置值到redis
            redisTemplate.opsForValue().set(session.getAttribute("userSession"), number + 1,OverDate.overTime(), TimeUnit.SECONDS);
        }
        //从redis获取值
        Integer number = (Integer) redisTemplate.opsForValue().get(session.getAttribute("userSession"));
        return number;
    }

    @GetMapping("find")
    public Integer findUserNumber(HttpSession session) {
        //从redis获取值
        Integer number = (Integer) redisTemplate.opsForValue().get(session.getAttribute("userSession"));
        return number;
    }
}
